package controller

import (
	"github.com/labstack/echo"
	"net/http"
	model "../model"
	lib "../lib"
	"fmt"
)



type User struct {
	Controller
}
func (this *User) Index (c echo.Context) error {
	return c.String(http.StatusOK, "Hello, World!")
}
func (this *User) Register (c echo.Context) error {

	x := lib.GetDbEngine()
	phone := c.FormValue("phone")
	password := c.FormValue("password")

	usersModel := &model.Users{Phone:phone}
	has, err := x.Get(usersModel)
	if err != nil {
		fmt.Println(err.Error())
	}
	if has {
		return c.String(http.StatusOK, "账号已经存在")
	} else {

		usersModel := &model.Users{Phone:phone, Password:lib.PasswordBcrypt(password)}
		affected,err := x.Insert(usersModel)
		if err != nil {
			return c.String(http.StatusOK, err.Error())
		}
		if affected > 0 {
			return c.String(http.StatusOK, "success")
		}
	}
	return c.String(http.StatusOK, "出了问题")
}
func (this *User) Login (c echo.Context) error {
	x := lib.GetDbEngine()
	phone := c.FormValue("phone")
	password := c.FormValue("password")

	usersModel := &model.Users{Phone:phone}
	has, err := x.Get(usersModel)
	if err != nil {
		fmt.Println(err.Error())
	}
	if has {
		if !lib.ComparePassword(usersModel.Password,password) {
			return c.JSON(http.StatusOK, this.RespondApi(20001,"密码错误",[]int{}))
		}
		return c.JSON(http.StatusOK, this.RespondApi(200,"success",[]int{}))
	} else {
		return c.JSON(http.StatusOK, this.RespondApi(20001,"账号不存在",[]int{}))
	}
}